package com.ferdict;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

// http://deltafalcon.com/2010/04/mounting-an-android-emulator-sd-card-image-in-windows/
// mounting sdcard to preload photos

public class ShareActivity extends Activity implements OnClickListener {
	private static final String tag = "UploadActivity";

	private String authToken;
	private Outfit currentOutfit;
	private long outfitId;
	private int curOutfitIdIndex;
	private List<Outfit> outfitList;
	private int numOutfitsShared;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share);

		numOutfitsShared = 0;
		authToken = getIntent().getStringExtra("token");

		getMyOutfits();
		updatePhoto();
		updateName();

		findViewById(R.id.share_prev_button_id).setOnClickListener(this);
		findViewById(R.id.share_next_button_id).setOnClickListener(this);

		findViewById(R.id.unshare_button_id).setOnClickListener(this);
		findViewById(R.id.share_done_button_id).setOnClickListener(this);
		findViewById(R.id.share_button_id).setOnClickListener(this);

	}

	void updatePhoto() {
		((ImageView) findViewById(R.id.share_image_view_id_your_photos))
				.setImageBitmap(getImageBitmap(currentOutfit.getPhotoUrl()));
	}

	private Bitmap getImageBitmap(String url) {
		Bitmap bm = null;
		try {
			URL aURL = new URL(url);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
		} catch (IOException e) {
			Log.e(tag, "Error getting bitmap", e);
		}
		return bm;
	}

	void updateName() {
		((TextView) findViewById(R.id.share_text_view_id))
				.setText(currentOutfit.getName());
		((ImageView) findViewById(R.id.share_outfit_state_id))
				.setImageDrawable(new BitmapDrawable(BitmapFactory
						.decodeResource(getResources(), (currentOutfit
								.isShare()) ? R.drawable.unlock_48
								: R.drawable.lock_48)));
		if (currentOutfit.isShare()) {
			((ImageButton) findViewById(R.id.unshare_button_id))
					.setEnabled(true);
			((ImageButton) findViewById(R.id.share_button_id))
					.setEnabled(false);
		} else {
			((ImageButton) findViewById(R.id.share_button_id)).setEnabled(true);
			((ImageButton) findViewById(R.id.unshare_button_id))
					.setEnabled(false);
		}
	}

	void getMyOutfits() {
		try {
			String jsonList = RestClient.doGet(Constants.SERVER,
					Constants.PORT, Constants.OUTFITS_URL + "?token="
							+ authToken);
			Log.w(tag, "JSON STR = " + jsonList);
			JSONArray outfitsArray = new JSONArray(jsonList);
			outfitList = new ArrayList<Outfit>();
			for (int i = 0; i < outfitsArray.length(); i++) {
				JSONObject o = outfitsArray.getJSONObject(i);
				Outfit outfit = new Outfit.Builder().outfitId(o.getLong("id"))
						.name(o.getString("name")).photo(o.getString("photo"))
						.numLikes(o.getInt("likes"))
						.numDislikes(o.getInt("dislikes"))
						.owner(o.getLong("owner")).share(o.getBoolean("share"))
						.build();
				outfitList.add(outfit);

				if (0 == i) {
					currentOutfit = outfit;
					curOutfitIdIndex = 0;
				}
			}
		} catch (Exception e) {
			Log.e(tag, "Could not get a list of outfits!", e);
		}
	}

	// @Override
	public void onClick(View v) {
		Toast t = null;

		switch (v.getId()) {
		case R.id.share_prev_button_id:
			Log.i(tag, "curIndex = " + curOutfitIdIndex);
			if (curOutfitIdIndex == outfitList.size() - 1) {
				t = Toast.makeText(this, "No older outfits available.",
						Toast.LENGTH_SHORT);
				t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				t.show();
				break;
			}
			currentOutfit = outfitList.get(++curOutfitIdIndex);
			updatePhoto();
			updateName();
			break;
		case R.id.share_next_button_id:
			if (curOutfitIdIndex == 0) {
				t = Toast.makeText(this, "No newer outfits available.",
						Toast.LENGTH_SHORT);
				t.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
				t.show();
				break;
			}
			currentOutfit = outfitList.get(--curOutfitIdIndex);
			updatePhoto();
			updateName();
			break;
		case R.id.share_done_button_id:
			Intent resultIntent = new Intent();
			resultIntent.putExtra("numOutfitsShared", numOutfitsShared);
			setResult(RESULT_OK, resultIntent);
			finish();
			break;
		case R.id.share_button_id:
			try {
				RestClient.doPut(
						Constants.SERVER,
						Constants.PORT,
						Constants.OUTFITS_URL + "?id="
								+ currentOutfit.getOutfitId() + "&token="
								+ authToken + "&share=1", "");

				Toast.makeText(
						ShareActivity.this,
						String.format("Outfit(name='%s') shared.",
								currentOutfit.getName()), Toast.LENGTH_SHORT)
						.show();

				((ImageView) findViewById(R.id.share_outfit_state_id))
						.setImageDrawable(new BitmapDrawable(BitmapFactory
								.decodeResource(getResources(),
										R.drawable.unlock_48)));
				((ImageButton) findViewById(R.id.share_button_id)).setEnabled(false);
				((ImageButton) findViewById(R.id.unshare_button_id))
						.setEnabled(true);
				numOutfitsShared++;
				break;
			} catch (Exception e) {
				Toast.makeText(
						ShareActivity.this,
						String.format("Could not share Outfit(name='%s')!",
								currentOutfit.getName()), Toast.LENGTH_SHORT)
						.show();
				Log.e(tag, String.format("Cannot share outfit(name=%s).",
						currentOutfit.getName()), e);
			}
			break;
		case R.id.unshare_button_id:
			try {
				RestClient.doPut(
						Constants.SERVER,
						Constants.PORT,
						Constants.OUTFITS_URL + "?id="
								+ currentOutfit.getOutfitId() + "&token="
								+ authToken + "&share=0", "");

				Toast.makeText(
						ShareActivity.this,
						String.format("Outfit(name='%s') UNshared.",
								currentOutfit.getName()), Toast.LENGTH_SHORT)
						.show();
				
				((ImageView) findViewById(R.id.share_outfit_state_id))
				.setImageDrawable(new BitmapDrawable(BitmapFactory
						.decodeResource(getResources(),
								R.drawable.lock_48)));
				((ImageButton) findViewById(R.id.share_button_id)).setEnabled(true);
				((ImageButton) findViewById(R.id.unshare_button_id))
						.setEnabled(false);
				numOutfitsShared++;
				break;
			} catch (Exception e) {
				Toast.makeText(
						ShareActivity.this,
						String.format("Could not UNshare Outfit(name='%s')!",
								currentOutfit.getName()), Toast.LENGTH_SHORT)
						.show();
				Log.e(tag, String.format("Cannot UNshare outfit(name=%s).",
						currentOutfit.getName()), e);
			}
			break;
		}
	}
}